package com.uplift.mobile.rate.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.uplift.common.utils.UUIDGenerater;
import com.uplift.mobile.rate.dao.RateMapper;
import com.uplift.mobile.rate.model.Rate;
import com.uplift.mobile.rate.service.IRateService;
import com.uplift.mobile.sys.model.DictModel;
import com.uplift.mobile.sys.service.IDictService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class rateServiceImpl implements IRateService {

    @Autowired
    private IDictService dictService;
    @Autowired
    private RateMapper rateMapper;

    @Value("${juhe.userkey}")
    private String juheUserKey;

    @Override
    public void updateRate() {
        DictModel dictModel = new DictModel();
        dictModel.setType("moneyType");
        List<Map<String, Object>> moneys = dictService.queryDict(dictModel);
        if(moneys==null || moneys.size()==0) {
            return;
        }

        BigDecimal rate = null;

        Map<String, Object> rateMap = null;
        Rate rateModel = null;
        for (Map<String, Object> money : moneys) {
            rate = getRateByMoneyType(money.get("code").toString());
            if(rate == null) {
                continue;
            }

            rateMap = queryMoenyRate(money.get("code").toString());
            rateModel = new Rate();
            if(rateMap.get("desc") != null) {
                String[] desc = StringUtils.split(rateMap.get("desc").toString(), ",");
                if(desc!=null && desc.length>=2) {
                    rateModel.setSymbol(desc[1]);
                }
            }

            if(rateMap == null) {
                rateModel.setMoneyType(money.get("code").toString());
                rateModel.setId(UUIDGenerater.generate());
                rateModel.setRate(rate);

                rateMapper.insertRate(rateModel);
            } else {
                rateModel.setId(rateMap.get("id").toString());
                rateModel.setRate(rate);
                rateModel.setUpdateTime(new Date());
                rateMapper.updateRate(rateModel);
            }
        }

    }

    @Override
    public Map<String, Object> queryMoenyRate(String moneyType) {
        if(StringUtils.isBlank(moneyType)) {
            return null;
        }

        Rate rate = new Rate();
        rate.setMoneyType(moneyType);

        List<Map<String, Object>> rates = rateMapper.selectInfo(rate);
        if(rates==null || rates.size()==0) {
            return null;
        }

        return rates.get(0);
    }

    private BigDecimal getRateByMoneyType(String moneyKey) {
        if(StringUtils.isBlank(moneyKey)) {
            return null;
        }

        if(StringUtils.equals(moneyKey, "JPY")) {           //如果是日元不需要获取汇率
            return null;
        }

        //获取聚合数据汇率信息
        String urlStr = "http://op.juhe.cn/onebox/exchange/currency?key="+juheUserKey+"&from=JPY&to="+moneyKey;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(urlStr);
        try {
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            if(httpResponse.getStatusLine().getStatusCode() == 200){
                String srtResult = "";
                srtResult = EntityUtils.toString(httpResponse.getEntity());//获得返回的结果
                if(StringUtils.isNoneBlank(srtResult)) {
                    JSONObject rateJson = JSONObject.parseObject(srtResult);
//                    if(StringUtils.equals(rateJson.getString("reason"), "successed")) {
                        JSONArray results = rateJson.getJSONArray("result");
                        if(results!=null && results.size()>0) {
                            JSONObject result = results.getJSONObject(0);
                            String rateStr = result.getString("result");
                            if(StringUtils.isNoneBlank(rateStr)) {
                                return new BigDecimal(rateStr);
                            }
                        }
//                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();

            return null;
        }finally {
            try {
                httpClient.close();//释放资源
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
